const _ = require('lodash');
const prefix = '/api/vps';
const shortid = require('shortid');
const moment = require('moment');
moment.locale('zh-cn');

module.exports = app => {
  const {router, model, middleware} = app;

  /** 批量添加vps */
  router.post(prefix + '/bulk-create', middleware.checkLogin, async ctx => {
    const list = ctx.request.body;
    if (_.isEmpty(list))
      return ctx.helper.error('没有提交数据');

    const ips = list.map(vps => vps.ip);
    const check = await model.Vps.findAll(
      {where: {ip: {[app.Sequelize.Op.in]: ips}}});
    if (check.length > 0) {
      const repeatIps = check.map(vps => vps.ip);
      return ctx.helper.error('操作失败，有IP重复了:' + repeatIps.join(','));
    }
    list.forEach(vps => vps.token = shortid.generate());
    await model.Vps.bulkCreate(list);

    //更新代码压缩包
    await ctx.service.zip.zipSpiderCode();
    //再次读取，进行初始化
    const vps = await model.Vps.findAll(
      {where: {ip: {[app.Sequelize.Op.in]: ips}}});
    vps.forEach(async vps => {

      //初始化vps
      ctx.service.vps.init(vps);

      //vps下载代码
      await ctx.service.vps.downloadCode(vps);
      //vps启动程序
      await ctx.service.vps.execute(vps);
    });
    ctx.body = 'ok';
  });

  /** 修改 vps */
  router.post(prefix, middleware.checkLogin, async ctx => {
    const post = _.pick(ctx.request.body, ['id', 'ip', 'user', 'password']);
    if (_.compact([post.id, post.ip, post.user, post.password]).length !== 4) {
      return ctx.helper.error('缺少数据');
    }
    //修改vps
    if (post.id > 0) {
      const client = await model.Vps.findById(post.id);
      if (!client)
        return ctx.helper.error('不存在的VPS');
      await client.update(post);
    }
    ctx.body = 'ok';
  });

  /** 读取 vps 列表 */
  router.get(prefix, middleware.checkLogin, async ctx => {
    const clients = await model.Vps.findAll({raw: true});
    clients.forEach(client => {
      let status = '正在初始化';
      switch (client.status) {
        case 1:
          status = '成功初始化';
          break;
        case 2:
          status = '正在下发爬虫代码';
          break;
        case 3:
          status = '成功下发爬虫代码';
          break;
        case 4:
          status = '正常工作中';
          break;
        case -1:
          status = '无法登入服务器进行初始化';
          break;
        case -2:
          status = '与分布式系统断开';
          break;
      }
      client.status = status;
      client.last_update_code_at = moment(client.last_update_code_at).calendar();
    });
    const redisStatus = await app.redis.get('note:spider_mission_status');
    const status = {};
    if (redisStatus) {
      const _status = JSON.parse(redisStatus);
      status.lastTime = moment(_status.lastTime).calendar();
      const executedTimes = _.compact(_status['执行时间']);
      status.executedTimes = executedTimes.length;
      const times = [];
      executedTimes.forEach((time, index) => {
        if (index < (executedTimes.length - 1))
          times.push(
            moment(executedTimes[index + 1]).diff(moment(time), 'minute'));
      });

      console.log({times, length: status.executedTimes});

      status.averageTime = _.sum(times) / status.executedTimes;
    }
    ctx.body = {clients, status};
  });

  /** 删除 vps */
  router.post(prefix + '/remove', middleware.checkLogin, async ctx => {
    if (_.isEmpty(ctx.request.body.id))
      return ctx.helper.error('没有选择服务器');

    const vps = await model.Vps.findAll(
      {where: {id: {[app.Sequelize.Op.in]: ctx.request.body.id}}});
    if (vps.length === 0)
      return ctx.helper.error('没有选择服务器');
    vps.forEach(vps => {
      ctx.service.vps.kill(vps);//尝试关闭爬虫进程
      vps.destroy();
    });
    ctx.body = 'ok';
  });

  /** 更新vps的代码 */
  router.post(prefix + '/update', middleware.checkLogin, async ctx => {
    if (_.isEmpty(ctx.request.body.id))
      return ctx.helper.error('没有选择服务器');

    const vps = await model.Vps.findAll(
      {where: {id: {[app.Sequelize.Op.in]: ctx.request.body.id}}});
    if (vps.length === 0)
      return ctx.helper.error('没有选择服务器');

    await ctx.service.zip.zipSpiderCode();

    vps.forEach(vps => {
      //vps下载代码
      ctx.service.vps.downloadCode(vps);
    });
    ctx.body = 'ok';
  });

  /** 重设 vps  */
  router.post(prefix + '/reset', middleware.checkLogin, async ctx => {
    if (_.isEmpty(ctx.request.body.id))
      return ctx.helper.error('没有选择服务器');

    const vps = await model.Vps.findAll(
      {where: {id: {[app.Sequelize.Op.in]: ctx.request.body.id}}});
    if (vps.length === 0)
      return ctx.helper.error('没有选择服务器');

    await ctx.service.zip.zipSpiderCode();

    vps.forEach(async vps => {
      //vps下载代码
      await ctx.service.vps.kill(vps);
      await ctx.service.vps.deleteFolder(vps);
      await ctx.service.vps.init(vps);
      await ctx.service.vps.downloadCode(vps);
      await ctx.service.vps.execute(vps);
    });
    ctx.body = 'ok';
  });

  /** 启动 vps 爬虫程序 */
  router.post(prefix + '/execute', middleware.checkLogin, async ctx => {
    if (_.isEmpty(ctx.request.body.id))
      return ctx.helper.error('没有选择服务器');

    const vps = await model.Vps.findAll(
      {where: {id: {[app.Sequelize.Op.in]: ctx.request.body.id}}});
    if (vps.length === 0)
      return ctx.helper.error('没有选择服务器');

    vps.forEach(async vps => {
      //vps启动程序
      await ctx.service.vps.execute(vps);
    });
    ctx.body = 'ok';
  });

  /** 停止 vps 上的爬虫*/
  router.post(prefix + '/disconnect', middleware.checkLogin, async ctx => {
    if (_.isEmpty(ctx.request.body.id))
      return ctx.helper.error('没有选择服务器');

    const vps = await model.Vps.findAll(
      {where: {id: {[app.Sequelize.Op.in]: ctx.request.body.id}}});

    if (vps.length === 0)
      return ctx.helper.error('没有选择服务器');

    vps.forEach(vps => {
      ctx.service.vps.kill(vps);
    });

    ctx.body = '已经发送停止命令';

  });

  //测试代码 todo 测试完毕需要删除
  router.get(prefix + '/test', middleware.checkLogin, async ctx => {
    const [platforms, tags] = await Promise.all([
      model.Platform.findAll(
        {raw: true, attributes: ['id', 'tag'], where: {disabled: false}}),
      model.PlatformTag.findAll({
        include: [{model: model.Platform}, {model: model.Type}],
      }),
    ]);

    //发送任务：抓取第一页列表，后续页面会自动处理
    platforms.forEach(p => {
      ctx.service.spiderTask.randomSendTask(
        {
          platform: p,
          test: true,
          type: 'firstPage',
          data: null,
        });
    });

    tags.forEach(tag => {
      ctx.service.spiderTask.randomSendTask(
        {
          platform: {id: tag.platform.id, tag: tag.platform.tag},
          test: true,
          type: 'firstTagPage',
          data: {tag: {key: tag.key}, type: {id: tag.type.id}},
        });
    });

    ctx.body = 'ok';
  });
};

